<template>
  <div class="product-detail-container">
    <!-- 返回按钮 -->
    <div class="back-button">
      <button @click="goBack">&larr; 返回</button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-spinner">
      <div class="spinner"></div>
      <p>加载产品详情中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error-message">
      <p>⚠️ 加载产品详情失败: {{ error }}</p>
      <button @click="fetchProduct">重试</button>
    </div>

    <!-- 产品详情 -->
    <div v-if="product" class="product-detail">
      <!-- 产品基本信息 -->
      <div class="product-header">
        <div class="product-image">
          <img
            v-if="product.img_url"
            :src="product.img_url"
            :alt="product.name"
            class="detail-img"
            @error="handleImageError"
          >
          <div v-else class="image-placeholder">
            <div class="financial-icon">💰</div>
          </div>
        </div>

        <div class="product-title">
          <h1>{{ product.name }}</h1>
          <div class="product-code">产品代码: {{ product.code }}</div>
          <div class="product-tags">
            <span v-if="product.is_hot" class="tag hot">热门</span>
            <span v-if="product.is_new" class="tag new">新品</span>
          </div>
        </div>

        <div class="product-meta">
          <span class="category-tag">{{ product.category.name }}</span>
          <div class="product-rating">
            <div class="stars">
              <span v-for="n in 5" :key="n" :class="{ 'active': n <= Math.round(average_rating) }">★</span>
            </div>
            <span class="rating-value">{{ average_rating.toFixed(1) }} ({{ review_count }}条评价)</span>
          </div>
        </div>
      </div>

      <!-- 产品内容 -->
      <div class="product-content">
        <!-- 左侧产品详情 -->
        <div class="product-info">
          <!-- 产品特点 -->
          <div class="section features-section">
            <h2>产品特点</h2>
            <div class="features-content" v-html="formatFeatures(product.features)"></div>
          </div>

          <!-- 保障详情 -->
          <div class="section coverage-section">
            <h2>保障详情</h2>
            <div class="coverage-grid">
              <div class="coverage-item" v-if="product.premium">
                <div class="coverage-label">保费</div>
                <div class="coverage-value">¥{{ product.premium }}</div>
              </div>
              <div class="coverage-item" v-if="product.coverage_amount">
                <div class="coverage-label">保额</div>
                <div class="coverage-value">¥{{ formatAmount(product.coverage_amount) }}</div>
              </div>
              <div class="coverage-item" v-if="product.coverage_period">
                <div class="coverage-label">保障期限</div>
                <div class="coverage-value">{{ product.coverage_period }}</div>
              </div>
              <div class="coverage-item">
                <div class="coverage-label">风险等级</div>
                <div class="coverage-value" :class="getRiskClass(product.risk_level)">
                  {{ getRiskText(product.risk_level) }}
                </div>
              </div>
            </div>
          </div>

          <!-- 产品描述 -->
          <div class="section description-section">
            <h2>产品描述</h2>
            <p>{{ product.description }}</p>
          </div>

          <!-- MongoDB 数据展示 -->
          <div class="section mongo-section">
            <h2>用户讨论</h2>
            <div class="mongo-content"  v-if="mongoData">
              <div v-for="(item, index) in mongoData" :key="index" class="mongo-item">
                <div class="mongo-user">{{ item.nickname }}</div>
                <div class="mongo-text">{{ item.content }}</div>
              </div>
            </div>
            <div class="mongo-input">
              <textarea v-model="mongoInput" placeholder="发表您的看法..." rows="3"></textarea>
              <button @click.prevent="postMongoMessage">提交</button>
            </div>
          </div>
        </div>

        <!-- 右侧操作面板 -->
        <div class="product-actions">
          <div class="action-card">
            <div class="action-price">
              <div class="price-label">价格</div>
              <div class="price-value">¥{{ product.price }}</div>
            </div>

            <div class="action-buttons">
              <button class="consult-btn">咨询AI顾问</button>
              <button
                class="buy-now-btn"
                @click="buyNow"
                :disabled="buyLoading"
              >
                <span v-if="buyLoading">处理中...</span>
                <span v-else>立即购买</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户评价 -->

      <!-- 相关产品 -->
      <div v-if="related_products.length > 0" class="related-products">
        <h2>相关产品推荐</h2>
        <div class="products-grid">
          <div
            v-for="product in related_products"
            :key="product.id"
            class="product-card"
            @click="viewProductDetail(product.id)"
          >
            <div class="product-image">
              <img
                v-if="product.img_url"
                :src="product.img_url"
                :alt="product.name"
                class="related-img"
                @error="handleImageError"
              >
              <div v-else class="image-placeholder">
                <div class="financial-icon">💰</div>
              </div>
            </div>
            <div class="product-info">
              <div class="card-header">
                <h3>{{ product.name }}</h3>
                <span class="category-tag">{{ product.category.name }}</span>
              </div>
              <div class="price-stock">
                <span class="price">¥{{ product.price }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  name: 'ProductDetailView',
  data() {
    return {
      product: null,
      reviews: [],
      related_products: [],
      average_rating: 0,
      review_count: 0,
      loading: true,
      error: null,
      showReviewForm: false,
      newReview: {
        rating: 5,
        content: ''
      },
      buyLoading: false,
      mongoData: null,
      mongoInput: ''
    };
  },
  created() {
    this.fetchProduct();
    this.fetchMongoData();
  },
  methods: {
    async fetchProduct() {
      this.loading = true;
      this.error = null;

      try {
        const productId = this.$route.params.id;
        if (!productId || isNaN(productId)) {
          throw new Error('无效的产品ID');
        }

        const userId = localStorage.getItem('user_id');
        const response = await axios.get(`http://127.0.0.1:8000/goods/products/${productId}/`, {
          params: { userid: userId }
        });
        const data = response.data;

        this.product = data.product;
        this.reviews = data.reviews;
        this.related_products = data.related_products;
        this.average_rating = data.average_rating;
        this.review_count = data.review_count;

      } catch (err) {
        console.error('获取产品详情失败:', err);
        this.error = err.response?.data?.detail || err.message || '服务器错误';
      } finally {
        this.loading = false;
      }
    },
    async fetchMongoData() {
      try {
        const response = await axios.get('http://127.0.0.1:8000/goods/mongo/', {
          params: {
            sid: this.$route.params.id
          }
        });
        console.log('MongoDB响应数据:', response.data); // 添加调试日志
        this.mongoData = Array.isArray(response.data.data)
          ? response.data.data
          : [response.data.data]; // 确保总是数组
        console.log('处理后数据:', this.mongoData); // 检查最终数据
      } catch (error) {
        console.error('获取MongoDB数据失败:', error);
        this.mongoData = []; // 确保失败时也是数组
      }
    },

    async postMongoMessage() {

      try {
        const message = {
          nickname: localStorage.getItem('phone') || '匿名用户',
          content: this.mongoInput,
          sid: this.$route.params.id,
          created_at: new Date().toISOString()
        };

        await axios.post('http://127.0.0.1:8000/goods/mongo/', message);
        this.mongoInput = '';
        this.fetchMongoData();
      } catch (error) {
        console.error('提交MongoDB数据失败:', error);
        ElMessage.error('提交失败，请重试');
      }
    },

    async buyNow() {
      const userId = localStorage.getItem('user_id');
      if (!userId) {
        ElMessage.warning('请先登录');
        return;
      }

      try {
        this.buyLoading = true;
        const response = await axios.post('http://127.0.0.1:8000/orders/order_add/', {
          product_id: this.product.id,
          user_id: userId,
          quantity: 1,
          price: this.product.price
        });

        if (response.data.status === 201 || response.data.code === 200) {
          ElMessage.success('购买成功！');
        } else if (response.data.msg?.includes('无法重复购买')) {
          ElMessage.warning('您已购买过该商品，无法重复购买');
        } else {
          ElMessage.error(response.data.msg || '购买失败');
        }
      } catch (error) {
        console.error('购买出错:', error);
        const errorMsg = error.response?.data?.msg || '购买失败，请稍后重试';
        ElMessage.error(errorMsg);
      } finally {
        this.buyLoading = false;
      }
    },

    async submitReview() {
      const userId = localStorage.getItem('user_id');
      if (!userId) {
        ElMessage.warning('请先登录');
        return;
      }

      try {
        const response = await axios.post('http://127.0.0.1:8000/goods/reviews/', {
          ...this.newReview,
          user_id: userId,
          product_id: this.product.id
        });

        if (response.data.code === 200) {
          ElMessage.success('评价提交成功！');
          this.showReviewForm = false;
          this.newReview = {
            rating: 5,
            content: ''
          };
          await this.fetchProduct();
        }
      } catch (error) {
        console.error('提交评价失败:', error);
        ElMessage.error('提交评价失败: ' + (error.response?.data?.message || error.message));
      }
    },

    goBack() {
      this.$router.go(-1);
    },
    formatAmount(amount) {
      if (amount >= 1000000) return (amount / 1000000).toFixed(1) + '百万';
      if (amount >= 10000) return (amount / 10000).toFixed(1) + '万';
      return amount;
    },
    formatFeatures(features) {
      return features?.replace(/\n/g, '<br>').replace(/\|/g, ' • ') || '';
    },
    getRiskClass(level) {
      return {
        'low': 'risk-low',
        'medium': 'risk-medium',
        'high': 'risk-high'
      }[level] || 'risk-medium';
    },
    getRiskText(level) {
      return {
        'low': '低风险',
        'medium': '中风险',
        'high': '高风险'
      }[level] || '中风险';
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });
    },
    getUserInitial(username) {
      return username?.charAt(0) || 'U';
    },
    handleImageError(event) {
      const placeholder = event.target.parentElement.querySelector('.image-placeholder');
      if (placeholder) {
        event.target.style.display = 'none';
        placeholder.style.display = 'flex';
      } else {
        event.target.parentElement.innerHTML = `
          <div class="image-placeholder">
            <div class="financial-icon">${event.target.alt?.charAt(0) || '💰'}</div>
          </div>
        `;
      }
    },
    viewProductDetail(productId) {
      this.$router.push(`/products/${productId}`);
      this.fetchProduct();
      this.fetchMongoData();
    }
  }
}
</script>

<style scoped>
/* 原有样式保持不变，新增以下样式 */

.product-tags {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}

.tag {
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
}

.tag.hot {
  background-color: #ff4757;
  color: white;
}

.tag.new {
  background-color: #2ed573;
  color: white;
}

.stars .active {
  color: #f6c23e;
}

.mongo-section {
  margin-top: 30px;
}

.mongo-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.mongo-user {
  font-weight: bold;
  margin-bottom: 5px;
}

.mongo-text {
  line-height: 1.6;
}

.mongo-input {
  margin-top: 15px;
}

.mongo-input textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  min-height: 80px;
}

.mongo-input button {
  margin-top: 10px;
  padding: 8px 15px;
  background: #4e73df;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
}

.mongo-input button:hover {
  background: #2e59d9;
}

.mongo-input button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f8f9fc;
  min-height: 100vh;
}

.back-button {
  margin-bottom: 20px;
}

.back-button button {
  background: #4e73df;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1rem;
  transition: background 0.3s;
}

.back-button button:hover {
  background: #2e59d9;
}

.product-header {
  background: white;
  padding: 25px;
  border-radius: 10px;
  box-shadow: 0 3px 15px rgba(0,0,0,0.05);
  margin-bottom: 25px;
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
}

.product-image {
  width: 300px;
  height: 200px;
  border-radius: 10px;
  overflow: hidden;
  background: linear-gradient(120deg, #f6f9ff 0%, #eef2f7 100%);
  flex-shrink: 0;
}

.detail-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-image:hover .detail-img {
  transform: scale(1.05);
}

.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 4rem;
  color: #4e73df;
  opacity: 0.2;
}

.product-title {
  flex: 1;
  min-width: 300px;
}

.product-title h1 {
  font-size: 2rem;
  color: #2e384d;
  margin-bottom: 10px;
}

.product-code {
  color: #6e707e;
  font-size: 0.95rem;
}

.product-meta {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.category-tag {
  background-color: #4e73df;
  color: white;
  padding: 5px 12px;
  border-radius: 15px;
  font-size: 0.9rem;
}

.product-rating {
  display: flex;
  align-items: center;
}

.stars {
  color: #f6c23e;
  font-size: 1.3rem;
  letter-spacing: 1px;
}

.rating-value {
  margin-left: 10px;
  color: #6e707e;
  font-size: 0.95rem;
}

.product-content {
  display: flex;
  gap: 25px;
  margin-bottom: 40px;
}

.product-info {
  flex: 1;
  background: white;
  padding: 25px;
  border-radius: 10px;
  box-shadow: 0 3px 15px rgba(0,0,0,0.05);
}

.product-actions {
  width: 350px;
}

.action-card {
  background: white;
  padding: 25px;
  border-radius: 10px;
  box-shadow: 0 3px 15px rgba(0,0,0,0.05);
  position: sticky;
  top: 20px;
}

.action-price {
  text-align: center;
  margin-bottom: 25px;
}

.price-label {
  color: #6e707e;
  font-size: 1rem;
}

.price-value {
  font-size: 2rem;
  font-weight: 700;
  color: #e74a3b;
  margin-top: 5px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.consult-btn, .buy-now-btn {
  padding: 14px;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.consult-btn {
  background: white;
  border: 2px solid #4e73df;
  color: #4e73df;
}

.consult-btn:hover {
  background: #f0f4ff;
}

.buy-now-btn {
  background: #4e73df;
  border: 2px solid #4e73df;
  color: white;
}

.buy-now-btn:hover {
  background: #2e59d9;
}

.product-stock {
  text-align: center;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.in-stock {
  color: #28a745;
  font-weight: 500;
}

.out-of-stock {
  color: #e74a3b;
  font-weight: 500;
}

.section {
  margin-bottom: 35px;
}

.section h2 {
  font-size: 1.5rem;
  color: #2e384d;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #f0f2f5;
}

.features-content {
  line-height: 1.8;
  color: #4a4f63;
}

.coverage-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.coverage-item {
  background: #f8f9fc;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid #eaeaea;
}

.coverage-label {
  color: #6e707e;
  font-size: 0.9rem;
  margin-bottom: 5px;
}

.coverage-value {
  font-size: 1.1rem;
  font-weight: 600;
  color: #2e384d;
}

.risk-low {
  color: #28a745;
}

.risk-medium {
  color: #f6c23e;
}

.risk-high {
  color: #e74a3b;
}

.description-section p {
  line-height: 1.8;
  color: #4a4f63;
}

.claim-steps {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.claim-step {
  display: flex;
  align-items: flex-start;
  width: calc(50% - 10px);
  margin-bottom: 20px;
}

.step-number {
  background: #4e73df;
  color: white;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 15px;
  flex-shrink: 0;
}

.step-content {
  line-height: 1.6;
  color: #4a4f63;
}

.reviews-section {
  background: white;
  padding: 25px;
  border-radius: 10px;
  box-shadow: 0 3px 15px rgba(0,0,0,0.05);
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.section-header h2 {
  font-size: 1.5rem;
  color: #2e384d;
  margin: 0;
}

.add-review-btn {
  background: #4e73df;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-weight: 500;
}

.review-form {
  background: #f8f9fc;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
  border: 1px solid #eaeaea;
}

.review-form h3 {
  margin-top: 0;
  color: #2e384d;
  margin-bottom: 20px;
}

.rating-input {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.rating-input label {
  width: 80px;
  color: #6e707e;
}

.stars-input {
  display: flex;
}

.stars-input span {
  font-size: 1.8rem;
  color: #d1d3e2;
  cursor: pointer;
  transition: color 0.2s;
  margin-right: 5px;
}

.star-selected {
  color: #f6c23e !important;
}

.review-form textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  margin-bottom: 15px;
  font-family: inherit;
  resize: vertical;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn, .submit-btn {
  padding: 8px 20px;
  border-radius: 5px;
  font-weight: 500;
  cursor: pointer;
}

.cancel-btn {
  background: #eaeaea;
  border: none;
  color: #6e707e;
}

.submit-btn {
  background: #4e73df;
  border: none;
  color: white;
}

.reviews-list {
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.review-item {
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  background: #4e73df;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 1.2rem;
  margin-right: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 500;
}

.review-date {
  color: #6e707e;
  font-size: 0.85rem;
}

.review-ratings {
  display: flex;
  gap: 15px;
}

.rating-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.rating-stars {
  color: #f6c23e;
  font-size: 1.1rem;
}

.review-content {
  color: #4a4f63;
  line-height: 1.6;
}

.claim-experience {
  margin-top: 10px;
  padding: 10px;
  background: #f8f9fc;
  border-radius: 5px;
  font-style: italic;
  border-left: 3px solid #4e73df;
}

.no-reviews {
  text-align: center;
  padding: 40px 0;
  color: #6e707e;
  border-top: 1px solid #eee;
}

.related-products {
  background: white;
  padding: 25px;
  border-radius: 10px;
  box-shadow: 0 3px 15px rgba(0,0,0,0.05);
}

.related-products h2 {
  font-size: 1.5rem;
  color: #2e384d;
  margin-bottom: 25px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 25px;
}

.product-card {
  border: 1px solid #eaeaea;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0,0,0,0.15);
  border-color: #4e73df;
}

.product-image {
  height: 150px;
  overflow: hidden;
  background: linear-gradient(120deg, #f6f9ff 0%, #eef2f7 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.related-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover .related-img {
  transform: scale(1.05);
}

.financial-icon {
  font-size: 3rem;
  color: #4e73df;
  opacity: 0.3;
}

.product-info {
  padding: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.card-header h3 {
  margin: 0;
  font-size: 1.1rem;
  color: #2e384d;
  flex: 1;
  font-weight: 600;
}

.category-tag {
  background-color: #4e73df;
  color: white;
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 0.7rem;
}

.price-stock {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-weight: bold;
  color: #e74a3b;
  font-size: 1.1rem;
}

/* 加载状态 */
.loading-spinner {
  text-align: center;
  padding: 100px 0;
}

.spinner {
  border: 4px solid rgba(78, 115, 223, 0.1);
  border-left-color: #4e73df;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  text-align: center;
  padding: 100px 0;
}

.error-message p {
  font-size: 1.2rem;
  color: #e74a3b;
  margin-bottom: 20px;
}

.error-message button {
  background-color: #4e73df;
  color: white;
  border: none;
  padding: 10px 25px;
  border-radius: 5px;
  cursor: pointer;
}

@media (max-width: 900px) {
  .product-content {
    flex-direction: column;
  }

  .product-actions {
    width: 100%;
  }

  .claim-steps {
    flex-direction: column;
  }

  .claim-step {
    width: 100%;
  }

  .product-header {
    flex-direction: column;
  }

  .product-image {
    width: 100%;
    height: 250px;
  }
}

@media (max-width: 600px) {
  .product-header,
  .product-info,
  .action-card,
  .reviews-section,
  .related-products {
    padding: 15px;
  }

  .product-title h1 {
    font-size: 1.7rem;
  }

  .coverage-grid {
    grid-template-columns: 1fr;
  }

  .review-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .product-image {
    height: 200px;
  }
}
</style>